//
//  SReactViewController.swift
//  RN
//
//  Created by HFY on 2021/1/19.
//

import UIKit
import React

class SReactDebuger {
    
    /// debug模式？
    var isDebug:Bool = false
    
    /// rn加载地址
    var host:String?
    
    /// rn加载端口
    var port:String?
}

class SReactViewController: UIViewController {
    
    var debuger:SReactDebuger = SReactDebuger()
    
    /// RN 应用标识符
    var rnName:String!
    
    /// RN 初始化属性
    var props:[String:Any]?
    
    /// RN页面
    var rootView:RCTRootView?
    
    deinit {
        debugPrint(Date(),"----->",#file,#function,#line)
    }
    
    required init(rnName:String,props:[String:Any]){
        super.init(nibName: nil, bundle: nil)
        self.rnName = rnName
        self.props = props
        SReactViewManager.shared.add(rn: self)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
        loadRN()
    }
    
    func setup() {
        
    }
    
    func commonProps(){
        
    }
    
    func loadRN(){
        assert(rnName != nil, "😭😭😭初始化没有指定应用标识符")
//        props?["id"] = SReactViewManager.shared.getRNID(rn: self) ?? ""
//        let rootView = RCTRootView.init(bridge: LoadBundle.shared.bridge!, moduleName: rnName, initialProperties: props)//init(bundleURL: jsCodeLocation, moduleName: rnName, initialProperties: props, launchOptions: nil)
//        rootView.backgroundColor = UIColor.white
//        rootView.frame = CGRect.init(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
//        view.addSubview(rootView)

        if debuger.isDebug {
            let port = debuger.port ?? "8081"
            let url = debuger.host ?? "http://localhost:\(port)/index.bundle?platform=ios&debug=true"
            if let jsCodeLocation = URL(string: url){
                props?["id"] = SReactViewManager.shared.getRNID(rn: self) ?? ""
                let rootView = RCTRootView.init(bundleURL: jsCodeLocation, moduleName: rnName, initialProperties: props, launchOptions: nil)
                rootView.backgroundColor = UIColor.white
                rootView.frame = CGRect.init(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
                view.addSubview(rootView)
            }
        }else{

        }

    }

}
